import { PlusOutlined } from '@ant-design/icons';
import {Button, Drawer, TreeSelect, message} from 'antd';
import React, { useState, useRef,useEffect } from 'react';
import {  FormattedMessage,KeepAlive } from 'umi';
import {PageContainer,FooterToolbar} from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {ModalForm, ProFormSelect, ProFormText} from '@ant-design/pro-form';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import { queryRule, updateRule, addRule,examineRule,removeRule } from './service';
import {history} from "@@/core/history";
import ProDescriptions, {ProDescriptionsItemProps} from "@ant-design/pro-descriptions";
import ProFormItem from "@ant-design/pro-form/lib/components/FormItem";



/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.RuleListItem) => {
  const hide = message.loading('正在添加');
  try {
    const res = await addRule({ ...fields });
    hide();
    if(res.status === 'ok'){
      message.success(res.message);
    }else {
      message.error(res.message);
    }
    return true;
  } catch (error) {
    hide();
    message.error('Adding failed, please try again!');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('执行中');
  try {
    const res = await updateRule({
      id: fields.id,
      pid: fields.pid,
      name: fields.name,
      path: fields.path,
      icon: fields.icon,
      sort: fields.sort,
      status: fields.status,
      type: fields.type,
      auth_open:fields.auth_open,
    });
    hide();

    if(res.status === 'ok'){
      message.success(res.message);
    }else {
      message.error(res.message);
    }
    return true;
  } catch (error) {
    hide();
    message.error('Configuration failed, please try again!');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.RuleListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    const res = await removeRule({
      id: selectedRows.map((row) => row.id),
    });
    hide();
    if(res.status === 'ok'){
      message.success(res.message);
    }else {
      message.error(res.message);
    }
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 修改状态
 *
 * @param selectedRows
 */
const handleExamine = async (selectedRows: API.RuleListItem[],status:number) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    const res = await examineRule({
      id: selectedRows.map((row) => row.id),
      status:status,
    });
    hide();
    if(res.status === 'ok'){
      message.success(res.message);
    }else {
      message.error(res.message);
    }
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);

  // 远程加载配置
  const [menus,setMenus] = useState([]);
  const sessionKey = history.location.pathname +'/treeData';
  useEffect(() => {
    if(sessionStorage.getItem(sessionKey)){
      const session = sessionStorage.getItem(sessionKey);
      setMenus(JSON.parse(session));
    }
  }, []);

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      title: '权限ID',
      dataIndex: 'id',
      hideInSearch: true,
      hideInForm:true,
      width:'120px',
    },
    {
      title: '权限名',
      dataIndex: 'name',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '控制器/方法',
      dataIndex: 'path',
    },
    {
      title: '图标',
      dataIndex: 'icon',
      tip:'使用antd pro 官方图标，可以直接复制保留文字使用',
      hideInSearch:true,
      initialValue:'SmileOutlined',
    },
    {
      title: '类型',
      dataIndex: 'type',
      sorter: true,
      hideInSearch:true,
      valueEnum: {1:'菜单',2:'按钮'},
      initialValue: '1',
    },
    {
      title: '权限状态',
      dataIndex: 'status',
      sorter: true,
      hideInSearch:true,
      valueEnum: {0:'禁用',1:'需要验证',2:'不需要验证'},
      initialValue: '1',
    },
    {
      title: '排序',
      dataIndex: 'sort',
      hideInSearch:true,
      tip:'按照数字升序排序，0排最前面',
      sorter: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            key="id"
            onClick={() => {
              handleUpdateModalVisible(true);
              setCurrentRow(record);
            }}
          >
            编辑
          </a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <KeepAlive>
        <ProTable<API.RuleListItem, API.PageParams>
          // headerTitle=''
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: 80,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                handleModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ]}
          request={async (params = {}, sorter, filter) =>
            queryRule({ ...params, sorter, filter }).then(response => {
              // 处理数据
              if(response.status === 'error'){
                if(response.message==='loginAgain'){
                  message.error('登录时间过期将在5秒后跳转到登录页面');
                  setTimeout(() => {
                    history.push('/user/login');
                  }, 5000);
                }else {
                  message.error(response.message);
                }
              }else{
                setMenus(response.data);
                sessionStorage.setItem(sessionKey,JSON.stringify(response.data));
              }
              return response;
            }).catch(info => {
              console.log('error', info);
            })
          }
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
      </KeepAlive>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            danger
          >
            批量删除
          </Button>
          <Button
            onClick={async () => {
              await handleExamine(selectedRowsState,0);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量禁用
          </Button>
          <Button type="primary"
                  onClick={async () => {
                    await handleExamine(selectedRowsState,1);
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  }}
          >
            批量开启
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title='新建'
        width="600px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.RuleListItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormItem
          name="pid"
          label="上级权限"
          tooltip="顶级权限直接留空"
          style={{width:'40%'}}
        >
          <TreeSelect
            showSearch
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择上级权限可以根据权限id搜索"
            allowClear
            treeDefaultExpandAll
            treeData={menus}
          />
        </ProFormItem>
        <ProFormText
          label="权限名"
          width="md"
          name="name"
          rules={[
            {
              required: true,
              message: '不能为空',
            },
          ]}
        />
        <ProFormText
          label="控制器/方法"
          width="md"
          name="path"
          tooltip="格式：AdData/index"
        />
        <ProFormText
          label="图标"
          width="md"
          name="icon"
          tooltip="使用antd pro 官方图标，可以直接复制保留文字使用"
          initialValue={'SmileOutlined'}
        />
        <ProFormSelect
          name="type"
          width="sm"
          label="权限类型"
          valueEnum={{
            1: '菜单',
            2: '按钮',
          }}
          initialValue={'1'}
        />
        <ProFormSelect
          name="status"
          width="sm"
          label="权限状态"
          valueEnum={{
            0:'禁用',1:'需要验证',2:'不需要验证'
          }}
          initialValue={'1'}
        />
        <ProFormText
          label="排序"
          width="sm"
          name="sort"
          initialValue={0}
        />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>

  );
};

export default TableList;
